/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package simplemessenger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Bill
 */
public class ConnectionManager {
    
    
    public ConnectionManager(boolean isClient)  {
        if (isClient) {
            setupClientConnection();//sets up program as a client
        } else {
            setupServerConnection();//sets up program as a server
        }
    }

    private void setupServerConnection()  {
        try {
            ServerSocket connection = new ServerSocket(4646); //create a socket to listen on
            while (true) {
                SendReceive sr = new SendReceive(connection.accept());//when a new connection is grabbed the accept method returns a socket from the serversocket class and passes it to the SendReceive class
            }
        } catch (IOException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);//TODO
        }
    }
    
    private void setupClientConnection() {
        try {
            Socket connection;//Declare Socket var
            Scanner s; //Declare Scanner var
            String host;//stores host info
            
            s = new Scanner(System.in);//initialize var s as a Scanner and provide it with an input stream of System.in << console inputstream
            System.out.print("Enter IP of server: ");//ui
            host = s.nextLine();//get the hostname from user and store in the host var
            connection = new Socket(host, 4646);//finally create the socket with the newly obtained data
            SendReceive sr = new SendReceive(connection);//create a SendReceive object with the newly created connection passed to it as a parameter
        } catch (UnknownHostException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);//TODO
        } catch (IOException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);//TODO
        }
    }
}
